import { Component, OnInit } from '@angular/core';

import { Player } from './player';
import { PlayerService } from './http-player.service';

@Component({
    moduleId: module.id,
    selector: 'guide-player-list',
    templateUrl: 'http-player-list.component.html',
    styles: ['.error {color:red;}']
})
export class HttpPlayerListComponent implements OnInit {
    errorMessage: string;
    players: Player[];
    mode = 'Observable';
    selectedPlayer: Player;
    originPlayer: Player;

    constructor(private playerService: PlayerService) { }

    ngOnInit() {
        this.getPlayers();
        // this.selectedPlayer = <Player>{};
    }
    getPlayers() {
        this.playerService.getPlayers()
            .subscribe(
            players => {
                this.players = players;
            },
            error => this.errorMessage = <any>error);
    }
    trackByPlayers(index: number, player: Player) {
        return player._id;
    }
    updatePlayer() {
        if (!this.selectedPlayer) {
            return;
        }
        if (this.selectedPlayer.name === this.originPlayer.name) {
            return;
        }
        this.playerService.updatePlayer(this.selectedPlayer).subscribe(() => {
            this.selectedPlayer = null;
            this.originPlayer = null;
            this.players = this.players.map((player, index) => {
                if (index === 1) {
                    return new Player(player._id + 1, player.name);
                } else {
                    return new Player(player._id, player.name);
                }
            });
        }, error => this.errorMessage = <any>error);
    }
    onSelect(player: Player) {
        this.selectedPlayer = player;
        this.originPlayer = JSON.parse(JSON.stringify(player));
    }
}